package org.example.liuy.controller;

import com.sun.net.httpserver.HttpExchange;
import lombok.extern.slf4j.Slf4j;
import org.example.liuy.annotation.GetMapping;
import org.example.liuy.annotation.RestController;
import org.example.liuy.exception.BusinessException;
import org.example.liuy.service.StakeManager;
import org.example.liuy.service.session.IntelligentSessionService;

import java.io.IOException;

/**
 * 投注查询控制器
 */
@Slf4j
@RestController
public class HighStakesController extends BaseController {

    private final StakeManager stakeManager;

    public HighStakesController(IntelligentSessionService sessionManager, StakeManager stakeManager) {
        super(sessionManager);
        this.stakeManager = stakeManager;
    }

    /**
     * 处理查询最高赌注请求
     * <p>
     * 接口要求：
     * 1. 仅保留每个客户针对该投注项的最高赌注（同一客户最多出现1次）
     * 2. 仅返回前20条最高赌注
     * 3. 无赌注时返回空字符串
     * </p>
     *
     * @param exchange HTTP交换对象，包含请求和响应信息
     * @throws IOException IO异常
     */
    @GetMapping("/{betOfferId}/highstakes")
    public void handleHighStakesRequest(HttpExchange exchange) throws IOException {
        try {
            Integer betOfferId = extractBetOfferId(exchange);
            String result = stakeManager.getHighStakes(betOfferId);

            exchange.getResponseHeaders().set("Content-Type", "text/csv");
            sendResponse(exchange, 200, result);
        } catch (BusinessException e) {
            handleBusinessException(exchange, e);
        } catch (Exception e) {
            log.error("High stakes request failed", e);
            sendResponse(exchange, 500, "Internal Server Error");
        }
    }

    /**
     * 从路径中提取投注项ID
     */
    private Integer extractBetOfferId(HttpExchange exchange) throws BusinessException {
        String[] pathParts = exchange.getRequestURI().getPath().split("/");
        if (pathParts.length < 3) {
            throw new BusinessException(BusinessException.PARAM_ERROE, "Invalid bet offer ID");
        }

        try {
            return Integer.valueOf(pathParts[pathParts.length - 2]);
        } catch (NumberFormatException e) {
            throw new BusinessException(BusinessException.PARAM_ERROE, "Invalid bet offer ID format");
        }
    }

    /**
     * 处理业务异常
     */
    private void handleBusinessException(HttpExchange exchange, BusinessException e) throws IOException {
        switch (e.getStatusCode()) {
            case BusinessException.PARAM_ERROE:
                sendResponse(exchange, 400, e.getMessage());
                break;
            case BusinessException.SYSTEM_MAXLIMIT:
                sendResponse(exchange, 429, e.getMessage()); // Too Many Requests
                break;
            default:
                sendResponse(exchange, 400, e.getMessage());
        }
    }
}
